package com.school.movie.common.component;

import com.school.movie.common.constant.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * @author swift
 */
@Component
@Slf4j
public class WebSocket implements WebSocketHandler {

    /**
     * 在线人数
     */
    private AtomicInteger onlineCount = new AtomicInteger(0);

    /**
     * 连接的客户端
     */
    private ConcurrentHashMap<String, WebSocketSession> clients = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        log.info("webSocket连接已建立" + this + " session:" + session);
        String phoneNumber = (String) session.getAttributes().get(Constants.User.WebSocket.USER_ID);
        if (!clients.containsKey(phoneNumber)) {
            onlineCount.incrementAndGet();
            clients.put(phoneNumber, session);
        }
        log.info("当前在线人数:" + onlineCount);
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) {
        log.debug("客户端传来消息");
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) {
        log.warn("消息传输出错");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
        log.info(session + "连接已关闭");
        String phoneNumber = (String) session.getAttributes().get(Constants.User.WebSocket.USER_ID);
        if (clients.containsKey(phoneNumber)) {
            clients.remove(phoneNumber);
            onlineCount.decrementAndGet();
        }
        log.info("当前在线人数:" + onlineCount);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    /**
     * 发送信息到指定客户端
     *
     * @param phoneNumber
     */
    public void sendMessageTo(String phoneNumber, WebSocketMessage<?> message) throws IOException {
        WebSocketSession clientSession = clients.get(phoneNumber);
        if (Objects.nonNull(clientSession)){
            clientSession.sendMessage(message);
        }
    }


}
 